package com.dayuanit.dy15.ebook.bookshop.service.impl;

import com.dayuanit.dy15.ebook.bookshop.entity.Address;
import com.dayuanit.dy15.ebook.bookshop.entity.Area;
import com.dayuanit.dy15.ebook.bookshop.mapper.AddressMapper;
import com.dayuanit.dy15.ebook.bookshop.mapper.AreaMapper;
import com.dayuanit.dy15.ebook.bookshop.service.AddressService;
import com.dayuanit.dy15.ebook.bookshop.util.StringUtils;
import com.dayuanit.dy15.ebook.bookshop.vo.AddressRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Area> listArea(byte level, long parentId) {
        return areaMapper.listByLevel(level, parentId);
    }

    @Override
    public void addAddress(AddressRequestVO addressRequestVO, long userId) {
        Area privince = areaMapper.selectByPrimaryKey((int)addressRequestVO.getSelPrivinceId());
        Area city = areaMapper.selectByPrimaryKey((int)addressRequestVO.getSelCityId());
        Area xian = areaMapper.selectByPrimaryKey((int)addressRequestVO.getSelXianId());

        if (addressRequestVO.getDefualtAddress().equals("1")) {
            //将之前的默认地址更新掉
            addressMapper.updateDefualtAddr(userId);
        }

        Address address = new Address();
        address.setArea(xian.getAreaname());
        address.setCity(city.getAreaname());
        address.setCreateTime(new Date());
        address.setDefaultAddr(addressRequestVO.getDefualtAddress().equals("1") ? 1 : 0);
        address.setDetailAddr(addressRequestVO.getAddressDetail());
        address.setModifyTime(address.getCreateTime());
        address.setPhone(addressRequestVO.getPhone());
        address.setProvince(privince.getAreaname());
        address.setRealName(addressRequestVO.getRealName());
        address.setStatus(1);
        address.setUserId(userId);

        addressMapper.insert(address);
    }

    @Override
    public List<Address> listUserAddress(long userId) {
        List<Address> addresses = addressMapper.listByUserId(userId);
        for (Address address : addresses) {
            address.setPhone(StringUtils.formatPhone(address.getPhone()));
        }
        return addresses;
    }
}
